<template>
  <div class="record-box" v-if="showRecord">
    <div class="head">
      <tabs :options="options" :tab="tab" class="tabes" @clickTab="clickTab" />
    </div>
    <div class="record-box-tbody">
      <PullRefresh v-model="listPayload.isRefresh" class="fresh-box" @refresh="freshHistory">
        <List
          v-model="listPayload.isLoading"
          :finished="listPayload.isFinished"
          finished-text="没有更多了～"
          @load="getMoreHistory"
          :immediate-check="false"
          :offset="100"
        >
          <ul class="list">
            <li v-for="(item, index) in numberList" :key="index" :style="tab === 1 ? 'height:34px' : 'height:46px'">
              <div class="cell_left">{{ item.periodsNumber }}期</div>
              <div class="drawingResult cell_right all-center space-around" v-if="tab === 1">
                <div v-for="(itm, idx) in item.numberList" :key="idx">
                  <div class="all-center">
                    <!-- <span :style="itm.symbolStyle" v-if="idx !=== 0">{{ itm.symbol }}</span> -->
                    <div :style="itm.numberStyle" class="number all-center">
                      {{ itm.number }}
                    </div>
                  </div>
                </div>
              </div>

              <div class="drawingResult cell_right all-center space-around" v-if="tab === 2">
                <div v-for="(itm, idx) in item.numberList.slice(0, 4)" :key="idx">
                  <div class="all-center">
                    <!-- <span :style="itm.symbolStyle" v-if="idx !=== 0">{{ itm.symbol }}</span> -->
                    <div :style="itm.numberStyle" class="number all-center">
                      {{ itm.number }}
                    </div>
                  </div>
                  <div class="spanStyle">
                    <span :style="itm.analyzeNumber.eo?.style">{{ itm.analyzeNumber.eo?.name }}</span>
                    <span :style="itm.analyzeNumber.size?.style">{{ itm.analyzeNumber.size?.name }}</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </List>
      </PullRefresh>
    </div>
  </div>
</template>

<script>
import { mapState } from 'pinia'
import tabs from '@/components/road/components/tabs.vue'
import { qxcHistory } from '@/components/road/constant'
import { useGameStore } from '@/stores/game'
import { findHistoryPage } from '@/api'
import { $utils } from '@/utils'
import { List, PullRefresh } from 'vant'

export default {
  components: {
    tabs,
    List,
    PullRefresh,
  },
  data() {
    return {
      showRecord: false, //显示记录
      loading: false,
      finished: false,
      headTile: [{ text: '期号' }],
      query: {
        current: 1,
        size: 10,
        lotteryCode: 'QXC',
      },
      recordData: {},
      total: 0, //总条数
      options: [],
      tab: 0,
      numberList: [],
      listPayload: {
        isLoading: false,
        isFinished: false,
        isRefresh: false,
        hasNextPage: false,
        totalPages: 1,
        fresh: true, // 刷新标记和请求接口标记
      },
      panel: {
        // 开奖号码的
        // symbolStyle: { color: '#008DDC', padding: '0 5px', fontSize: '15px' }, // + - = 的样式
        beforeStyle: { color: '#4D3EFF', border: '1px solid #4D3EFF', fontSize: '14px', background: '#fff' }, // =前号码的样式
      },
    }
  },
  created() {
    this.options = qxcHistory
    this.tab = qxcHistory[0].value
  },
  filters: {
    analyzeNumber: function (num) {
      let number = parseInt(num)
      if (number >= 0 && number <= 9) {
        const isEven = number % 2 === 0
        const isSmall = number < 5
        const result = {
          eo: {
            name: isEven ? '双' : '单',
            code: isEven ? 'odd' : 'even',
            style: isEven ? 'background:#FF9F0F;' : 'background:#4D3EFF;',
          },
          size: {
            name: isSmall ? '小' : '大',
            code: isSmall ? 'small' : 'big',
            style: isSmall ? 'background:#FF0404;' : 'background:#11D46B;',
          },
        }
        return result
      } else {
        return 'error number'
      }
    },
  },
  computed: {
    ...mapState(useGameStore, {
      drawingStatus: (state) => state.drawingStatus,
      currentGame: (state) => state.currentGame,
    }),
  },
  watch: {
    drawingStatus: {
      handler(newValue) {
        if (newValue.code === 50 && this.showRecord) {
          // 已开奖
          this.query.current = 1
          this.listPayload.fresh = true
          this.fetchHistory()
        }
      },
      deep: true,
    },
  },
  methods: {
    clickTab(tab) {
      this.tab = tab
      // console.log(tab, '---tab----')
      this.fetchHistory()
    },
    // 加载更多
    getMoreHistory() {
      if (this.query.current > this.listPayload.totalPages) {
        this.listPayload.isLoading = false
        this.listPayload.isFinished = true
        return
      }
      this.listPayload.isLoading = true
      this.listPayload.isFinished = false
      setTimeout(() => {
        this.query.current++
        this.fetchHistory(() => {
          this.listPayload.isLoading = false
          this.listPayload.isFinished = false
        })
      }, 500)
    },

    // 刷新数据
    freshHistory() {
      this.listPayload.fresh = true
      this.listPayload.isFinished = false
      this.query.current = 1
      setTimeout(() => {
        this.listPayload.isRefresh = true
        this.fetchHistory(() => {
          this.listPayload.isRefresh = false
          this.listPayload.isFinished = false
        })
      }, 1000)
    },
    // 获取历史数据
    async fetchHistory(cb = () => {}) {
      this.query.lotteryCode = this.currentGame
      const {
        data: { records, pages },
      } = await findHistoryPage(this.query)
      this.listPayload.totalPages = pages
      if (cb) cb()
      // if (!records[0].drawingResult) records.shift() //有可能存在最新一期还未开奖的情况，若最新一期还没开奖就将这一期剔除
      if (this.listPayload.fresh) {
        // 刷新数据
        this.numberList = []
        this.listPayload.fresh = false
        this.numberList = this.handleList(records)
        // this.$emit('drawingResult', this.list.slice(0, 1)[0]) // 将最新一期号码置顶上方
      } else {
        // 加载更多
        this.numberList = this.numberList.concat(this.handleList(records))
      }
      console.log(this.numberList, ' this.list=api')
    },
    handleList(list) {
      if ($utils.isEmpty(list)) return []
      list.forEach((item) => {
        const arr = []
        if ($utils.isEmpty(item.drawingResult)) return
        let numList = item.drawingResult.split(',')
        numList.map((numItem) => {
          let obj = {}
          obj.number = numItem
          obj.analyzeNumber = this.$options.filters['analyzeNumber'](numItem)
          // obj.symbol = '+';
          // obj.symbolStyle = this.panel.symbolStyle
          obj.numberStyle = this.panel.beforeStyle
          arr.push(obj)
        })
        // let sum = numList.reduce((prev, current) => Number(prev) + Number(current), 0);
        // arr.push({
        //   number: sum,
        //   // symbol: '=',
        //   symbolStyle: this.panel.symbolStyle,
        //   numberStyle: this.panel.afterStyle,
        // });
        item.numberList = arr
      })
      return list
    },
    // 显示或隐藏
    showOrHide() {
      const gameType = useGameStore().currentGame
      this.showRecord = !this.showRecord
      if (this.showRecord) {
        this.query = {
          current: 1,
          size: 50,
          lotteryCode: gameType,
        }
        // this.list = [];
        this.listPayload.totalPages = 1
        this.fetchHistory()
      }
    },
    open() {
      this.showRecord = true
    },
    close() {
      this.showRecord = false
    },
  },
}
</script>

<style scoped lang="less">
.record-box {
  padding-top: 6px;
  box-sizing: border-box;
  width: 100%;
  background: #171a26;
  position: absolute;
  top: -0;
  z-index: 99;
  max-height: 392px;
  min-height: 200px;
  left: 0;
  overflow: hidden;
  font-family: Inter;
  .title {
    font-size: 11px;
    color: #a2a9e6;

    &:nth-child(1) {
      width: 70px;
      font-size: 13px;
    }
  }
  &-thead {
    width: 100%;
    padding: 0 16px;
    box-sizing: border-box;
    font-family: Inter;
    font-size: 12px;
    line-height: 15px;
    text-align: center;
    .cell {
      min-height: 33px;
      display: flex;
      align-items: center;
    }
  }
  .head {
    padding: 0 14px;
    color: #a2a9e6;

    :deep(.tabes) {
      box-sizing: border-box;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 1px;
        bottom: 0;
        left: 0;
        background-color: #363d57;
      }
    }
  }
  .cell_left {
    width: 30%;
    text-align: center;
    color: #bdc4ff;
  }
  .cell_right {
    width: 65%;
    text-align: center;
    padding-left: 12px;
    box-sizing: border-box;
  }
  &-tbody {
    font-size: 13px;
    line-height: 16px;
    text-align: center;
    color: #6a6a6a;
    overflow-y: scroll;
    height: 260px;
    padding-top: 4px;
    .list {
      li {
        width: 100%;
        height: 34px;
        display: flex;
        align-items: center;
        padding: 0 16px;
        box-sizing: border-box;
        &:nth-child(even) {
          background: #212432;
        }
        .spanStyle {
          span {
            width: 14px;
            height: 14px;
            border-radius: 2px;
            display: inline-block;
            color: #ffffff;
          }
          span:nth-child(1) {
            margin-right: 3px;
          }
        }
        .drawingResult {
          span {
            line-height: 1;
          }
          .number {
            width: 24px;
            height: 24px;
            line-height: 1;
            border-radius: 16px;
          }
        }
      }
    }
  }
  :deep(.van-list) {
    padding-bottom: 40px;
    box-sizing: border-box;
  }
  :deep(.van-list__finished-text, .van-loading__text, .van-pull-refresh__head) {
    font-size: 12px;
  }
  .space-around {
    justify-content: space-around !important;
  }
}
</style>
